package com.akbar.filter;

import com.akbar.constant.JwtClaimsConstant;
import com.akbar.properties.JwtProperties;
import com.akbar.utils.JwtUtil;
import com.akbar.utils.ResponseUtil;
import com.akbar.utils.ResultUtil;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtException;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;

/**
 * Jwt 认证过滤器
 */
@Slf4j
@Component
public class JwtAuthenticationFilter extends OncePerRequestFilter {

    @Autowired
    private JwtUtil jwtUtil;

    @Autowired
    private JwtProperties  jwtProperties;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private UserDetailsService userDetailsService;


    @Override
    protected void doFilterInternal(HttpServletRequest request,
                                    HttpServletResponse response,
                                    FilterChain filterChain) throws ServletException, IOException {

        final String token = request.getHeader(jwtProperties.getTokenName());

        String username = null;


        // 解析token
        if (token != null) {
            try {
                String redisToken = redisTemplate.opsForValue().get(token);
                if(redisToken == null){
                    throw new  JwtException("Token 已失效");
                }
                Claims payload = jwtUtil.getPayload(token);
                username = payload.get(JwtClaimsConstant.USERNAME, String.class);
            } catch (Exception e) {
                log.error("解析 Token 时出错: {}", e.getMessage());

                ResponseUtil.writeJson(response,
                        HttpServletResponse.SC_UNAUTHORIZED,
                        ResultUtil.error(401, "Unauthorized: " + e.getMessage())
                        );

                // 终止当前过滤链和请求处理流程
                return;
            }
        }

        // 如果拿到了用户名且当前上下文还没有认证
        if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {

            // 从数据库或缓存加载用户
            UserDetails userDetails = userDetailsService.loadUserByUsername(username);

            if (jwtUtil.validateToken(token)) {

                // 手动构造认证信息
                UsernamePasswordAuthenticationToken authenticationToken  =
                        new UsernamePasswordAuthenticationToken(
                                userDetails,
                                null,
                                userDetails.getAuthorities()
                        );

                authenticationToken.setDetails(
                        new WebAuthenticationDetailsSource().buildDetails(request)
                );

                // 把认证信息放入上下文
                SecurityContextHolder.getContext().setAuthentication(authenticationToken);
            }
        }

        // 放行
        filterChain.doFilter(request, response);
    }
}
